package cn.iocoder.yudao.module.reading.dal.mysql.punch;

import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.reading.dal.dataobject.punch.PunchBookDO;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 打卡绘本关联 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface PunchBookMapper extends BaseMapperX<PunchBookDO> {

    /**
     * 根据打卡记录ID查询绘本关联列表
     *
     * @param punchId 打卡记录ID
     * @return 绘本关联列表
     */
    default List<PunchBookDO> selectByPunchId(Long punchId) {
        return selectList(new LambdaQueryWrapperX<PunchBookDO>()
                .eq(PunchBookDO::getPunchId, punchId)
                .orderByAsc(PunchBookDO::getReadAt));
    }

    /**
     * 根据打卡记录ID删除绘本关联
     *
     * @param punchId 打卡记录ID
     * @return 删除数量
     */
    default int deleteByPunchId(Long punchId) {
        return delete(PunchBookDO::getPunchId, punchId);
    }

    /**
     * 根据用户ID删除所有打卡绘本关联
     *
     * @param userId 用户ID
     * @return 删除数量
     */
    default int deleteByUserId(Long userId) {
        // 需要先查询用户的所有打卡记录，然后删除对应的绘本关联
        return delete(new LambdaQueryWrapperX<PunchBookDO>()
                .exists("SELECT 1 FROM punch_records pr WHERE pr.id = punch_books.punch_id AND pr.user_id = {0}", userId));
    }

    /**
     * 根据打卡记录ID列表查询绘本关联
     *
     * @param punchIds 打卡记录ID列表
     * @return 绘本关联列表
     */
    default List<PunchBookDO> selectByPunchIds(List<Long> punchIds) {
        return selectList(new LambdaQueryWrapperX<PunchBookDO>()
                .in(PunchBookDO::getPunchId, punchIds)
                .orderByAsc(PunchBookDO::getPunchId)
                .orderByAsc(PunchBookDO::getReadAt));
    }

}
